import { Col, Rate, Row, Spin } from "antd";
import { Card, Carousel, Flex, WhiteSpace, Toast } from "antd-mobile";
import { addon } from "pao-aop";
import { reactControl, ReactView, ReactViewControl, ReactViewState } from "pao-aop-client";
import React from "react";
import { getUuid, setMainFormTitle } from "src/business/util_tool";
import { AppServiceUtility } from "src/projects/app/appService";
import { encodeUrlParam, forceCheckIsLogin, PAGE_TYPE, ROUTE_PATH } from "src/projects/app/util-tool";
import { Activity } from "src/projects/models/activity";
import './index.less';

// TODO: 平台id以及慈善id均写死
const divideTitleMap = {
    '平台': '7e7e2fec-d91d-11e9-8e1d-983b8f0bcd67',
    '慈善': '567c9bd8-0208-11ea-9b57-7c2a3115762d',
    '服务商': ''
};
/**
 * 组件：商家详情视图控件状态
 */
export interface ServiceDetailsViewState extends ReactViewState {
    /** 数据 */
    data: Activity;
    /** 图片高度 */
    imgHeight?: number | string;
    /** 根据id获取的商家详情信息 */
    businessDetail?: any;
    /** 服务介绍 */
    introduce?: string;
    /** imgUrl */
    imgUrl?: any;
    /** 预约时间 */
    appointment_data?: any;
    loading: boolean;
    is_collection?: any;
}
/**
 * 组件：商家详情视图控件
 */
export class ServiceDetailsView extends ReactView<ServiceDetailsViewControl, ServiceDetailsViewState> {
    constructor(props: any) {
        super(props);

        this.state = {
            data: {},
            imgHeight: 176,
            businessDetail: {},
            introduce: '',
            imgUrl: [],
            appointment_data: '',
            loading: true,
            is_collection: 0
        };
    }
    componentDidMount() {
        setMainFormTitle("服务产品详情");
        let id = this.props.match!.params.key;
        // 查询是否收藏
        AppServiceUtility.service_follow_collection_service.get_service_follow_collection_list!({ business_id: id, type: 'collection', object: '居家服务', "is_own": true }, 1, 1)!
            .then((data: any) => {
                console.log(data);
                if (data.result.length > 0) {
                    this.setState({
                        is_collection: 1
                    });
                }
            });
        // 根据id获取服务详情
        AppServiceUtility.service_detail_service.get_service_product_item_package_list!({ 'id': id }, 1, 1)!
            .then((data: any) => {
                console.log(data);
                let service_ulr: any = [];
                if (data.result.length > 0) {
                    data.result[0].picture_collection ? data.result[0].picture_collection.map((value: any, index: number) => {
                        let obj = (
                            <a
                                className='carousel-a'
                                key={index}
                                href="javascript:;"
                                style={{ height: this.state.imgHeight }}
                            >
                                <img
                                    className='carousel-img'
                                    src={value}
                                    alt=""
                                    onLoad={() => {
                                        window.dispatchEvent(new Event('resize'));
                                        this.setState({ imgHeight: 'auto' });
                                    }}
                                />
                            </a>
                        );
                        service_ulr.push(obj);
                    })
                        :
                        '';
                    this.setState({
                        businessDetail: data.result[0],
                        loading: false,
                        imgUrl: service_ulr,
                        introduce: data.result[0].introduce,
                    });
                }
            });
    }

    onClickRow = (id: string) => {
        console.info(id);
        this.props.history!.push(ROUTE_PATH.childCommmentList + '/' + id);
    }
    pay = (date?: any) => {
        // let id = this.props.match!.params.key;
        // 判断是否登录
        // AppServiceUtility.personnel_service.get_user_session!()!
        //     .then((data: any) => {
        //         if (!data) {
        //             this.props.history!.push(ROUTE_PATH.login);
        //             return;
        //         }
        //     });
        let { businessDetail } = this.state;
        let j = businessDetail.total_price ? businessDetail.total_price : 0;
        // 数量为1
        let divide = {};
        if (businessDetail['proportion']) {
            businessDetail['proportion'].map((e: { title: string, contents: number }, i: number) => {
                switch (e.title) {
                    case "平台":
                        divide['平台'] = {
                            id: divideTitleMap['平台'],
                            percent: e.contents
                        };
                        break;
                    case "服务商":
                        divide["服务商"] = {
                            id: divideTitleMap["服务商"],
                            percent: e.contents
                        };
                        break;
                    case "慈善":
                        divide['慈善'] = {
                            id: divideTitleMap['慈善'],
                            percent: e.contents
                        };
                        break;
                    default:
                        break;
                }
            });
        } else {
            divide['平台'] = {
                id: divideTitleMap['平台'],
                percent: 0
            };
            divide["服务商"] = {
                id: divideTitleMap["服务商"],
                percent: 1
            };
            divide['慈善'] = {
                id: divideTitleMap['慈善'],
                percent: 0
            };
        }
        businessDetail['num'] = 1;
        // 服务订单列表所需数据
        let buy_list = [];
        let uuid = getUuid();
        // if (j) {
        buy_list.push({
            // 服务套餐id（必要）
            id: businessDetail['id'],
            // 单价（必要）
            price: j,
            // 数量（必要）
            num: 1,
            // 总价（必要）
            amount_total: businessDetail['num'] * j,
            picture_collection: businessDetail['picture_collection'],
            // 是否补贴账户（必要）
            subsidy: businessDetail['is_allowance'] === "1" ? j : 0,
            // 摘要（必要）
            abstract: businessDetail['name'],
            // 平台id（必要）
            pt_id: divide['平台']['id'],
            // 平台分成（必要）
            pt_percent: divide['平台']['percent'],
            // 服务商id（必要）
            fw_id: businessDetail['organization_id'],
            // 服务商分成（必要）
            fw_percent: divide['服务商']['percent'],
            // 慈善id（必要）
            cs_id: divide['慈善']['id'],
            // 慈善分成（必要）
            cs_percent: divide['慈善']['percent'],
            // 备注（必要）
            remarks: '居家服务商品',
            // appointment_data: date ? date : '',
        });
        // }
        const paramToSend = {
            // 判断是购买服务项目还是充值
            page_type: PAGE_TYPE.BUY,
            page_info: buy_list,
            // 商户唯一订单号（必要）
            out_trade_no: uuid,
            // 附加信息（可选），业务接受异步通知所需
            attach: '服务套餐',
            product_desc: "服务套餐购买",
            success_url: ROUTE_PATH.paymentSucceed,
            fail_url: ROUTE_PATH.paymentFail,
            // appointment_data: this.state.appointment_data,
        };
        const paramToSendStr = JSON.stringify(paramToSend);
        forceCheckIsLogin(
            this.props,
            {
                successPath: ROUTE_PATH.cleanSubmitOrder + '/' + encodeUrlParam(paramToSendStr)
            },
            {
                backPath: window.location.pathname
            }
        );
        // this.props.history!.push(ROUTE_PATH.cleanSubmitOrder + '/' + encodeUrlParam(paramToSendStr));
    }
    comment = () => {
        this.props.history!.push(ROUTE_PATH.comment2);
    }
    // changDate = (date: any) => {
    //     this.pay(date);
    // }
    // formatDate(date: any) {
    //     /* eslint no-confusing-arrow: 0 */
    //     const pad = (n: any) => n < 10 ? `0${n}` : n;
    //     const dateStr = `${date.getFullYear()}-${pad(date.getMonth() + 1)}-${pad(date.getDate())}`;
    //     const timeStr = `${pad(date.getHours())}:${pad(date.getMinutes())}`;
    //     return `${dateStr} ${timeStr}`;
    // }

    goBusinessDetail = () => {
        this.props.history!.push(ROUTE_PATH.serverDetail + '/' + this.state.businessDetail.organization_id);
    }

    follow = () => {
        if (this.state.is_collection === 0) {
            AppServiceUtility.service_follow_collection_service.update_service_follow_collection!(this.state.businessDetail.id, 'collection', '居家服务')!
                .then((datas: any) => {
                    if (datas === 'Success') {
                        this.setState(
                            {
                                is_collection: 1
                            },
                            () => {
                                Toast.success('收藏成功');
                            }
                        );
                    }
                });
        } else {
            AppServiceUtility.service_follow_collection_service.delete_service_follow_collection_by_business_id!({ busindess: this.state.businessDetail.id, type: 'collection', object: '居家服务' })!
                .then((datas: any) => {
                    if (datas === 'Success') {
                        this.setState(
                            {
                                is_collection: 0
                            },
                            () => {
                                Toast.success('取消收藏成功');
                            }
                        );
                    }
                });
        }
    }
    render() {
        let { businessDetail } = this.state;
        // let id = this.props.match!.params.key;
        // let type = this.props.match!.params.code;
        return (
            <Spin spinning={this.state.loading}>
                <div>
                    <div className='fucp-details' onClick={this.follow}>
                        <Rate value={this.state.is_collection} count={1} />
                    </div>
                    <Carousel
                        autoplay={true}
                        infinite={true}
                    >
                        {this.state.imgUrl.length > 0 ? this.state.imgUrl : <div style={{ textAlign: 'center' }}>没有图片数据</div>}
                    </Carousel>
                    <Card>
                        <Card.Body>
                            <Row>
                                <Col span={14} style={{ fontWeight: 'bold', fontSize: "20px" }}>{businessDetail.name}</Col>
                                <Col>评星：<Rate className='product-rate' count={5} value={businessDetail.comment_avg ? businessDetail.comment_avg : 0} /></Col>
                            </Row>
                            <WhiteSpace size='sm' />
                            <Row>
                                <Col>
                                    {businessDetail.length > 0 ? businessDetail.org_info[0].name : ''}
                                </Col>
                            </Row>
                            <WhiteSpace size='sm' />
                            <Row>
                                <Col span={10} style={{ color: "#108ee9" }}>
                                    ￥&nbsp;
                                <span style={{ fontSize: '20px' }}>{businessDetail.total_price ? businessDetail.total_price : 0}</span>
                                </Col>
                                <Col><span style={{ color: '#ffd800' }}>{businessDetail.pay_count ? businessDetail.pay_count : 0}</span>人购买</Col>
                            </Row>
                        </Card.Body>
                    </Card>
                    <WhiteSpace size="lg" />
                    <Card>
                        <Card.Body>
                            <Row>
                                <Col span={16}>{businessDetail.service_product_type}</Col>
                                <Col>总服务次数：<span style={{ color: '#ffd800' }}>{businessDetail.pay_count ? businessDetail.pay_count : 0}</span></Col>
                            </Row>
                            <WhiteSpace size='lg' />
                            <Row>
                                <Col>{businessDetail.name}</Col>
                            </Row>
                        </Card.Body>
                    </Card>
                    <WhiteSpace size="lg" />
                    <Card>
                        <Card.Header
                            title="服务简介"
                        />
                        <Card.Body>
                            {
                                this.state.introduce!.split('\n').map((value: any, index: number) => {
                                    return (
                                        <div key={index}>
                                            {value.indexOf('【') > -1 ? value : <span style={{ paddingLeft: '15px' }}>{value}</span>}
                                        </div>
                                    );
                                })
                            }
                        </Card.Body>
                    </Card>
                    <WhiteSpace size="lg" />
                    <WhiteSpace size="lg" />
                    <WhiteSpace size="lg" />
                    <WhiteSpace size="lg" />
                    <div style={{ position: 'fixed', bottom: '0px', right: "0px", height: '50px', width: '100%', background: '#fff' }}>
                        <Flex>
                            {/* <Flex.Item>
                            <DatePicker
                                mode="date"
                                title="预约时间"
                                extra="Optional"
                                format={val => `UTC Time: ${this.formatDate(val).split(' ')[1]}`}
                                value={this.state.appointment_data}
                                onChange={this.changDate}
                            >
                                <div style={{ width: '100%', height: '100%', textAlign: 'center', lineHeight: '50px', background: '#fff' }}>预约服务</div>
                            </DatePicker>
                        </Flex.Item> */}
                            <Flex.Item><div style={{ width: '100%', height: '100%', textAlign: 'center', lineHeight: '50px', background: '#fff', fontWeight: 'bold' }} onClick={this.goBusinessDetail}>服务商详情</div></Flex.Item>
                            <Flex.Item><div style={{ width: '100%', height: '100%', textAlign: 'center', lineHeight: '50px', background: 'red', color: '#fff', fontWeight: 'bold' }} onClick={this.pay}>立即购买</div></Flex.Item>
                        </Flex>
                    </div>
                </div>
            </Spin>
        );
    }
}

/**
 * 组件：商家详情视图控件
 * 控制商家详情视图控件
 */
@addon('FoodBusinessDetailsView', '商家详情视图控件', '控制商家详情视图控件')
@reactControl(ServiceDetailsView, true)
export class ServiceDetailsViewControl extends ReactViewControl {
    constructor() {
        super();
    }
}